using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(Camera))]
public class OrbitCamera : MonoBehaviour
{
    [SerializeField] [Header("Player Transform Object")]
    Transform player = default;

    [SerializeField, Range(1f, 20f)] private float distance = 5f;
    [SerializeField, Min(0f)] private float playerRadius = 1f;
    [SerializeField, Range(0f, 1f)] float focusCentering = 0.5f;

    private Vector3 focusPoint;

    private void Awake()
    {
        focusPoint = player.position;
    }

    private void LateUpdate()
    {
        UpdatePlayerPosition();
        Vector3 lookDirection = Vector3.forward;

        transform.localPosition = focusPoint - lookDirection * distance;
    }

    private void UpdatePlayerPosition()
    {
        Vector3 actuallyPosition = player.position;
        if (playerRadius > 0f)
        {
            float distanceO = Vector3.Distance(actuallyPosition, focusPoint);
            float t = 1f;
            if (distanceO > 0.01f && focusCentering > 0f)
            {
                t = Mathf.Pow(1f - focusCentering, Time.deltaTime);
            }
            if (distanceO > playerRadius)
            {
                t = Mathf.Min(t, playerRadius / distanceO);
            }
            focusPoint = Vector3.Lerp(actuallyPosition, focusPoint, t);
        }
        else
        {
            focusPoint = actuallyPosition;
        }
    }
}